function isHappy(n, pow) {
    var x = n;
    var out = [x]
    while (true) {
        x = [...'' + x].reduce((s, v) => s += (+v) ** pow, 0);
        if (out.includes(x)) { out.push(x); return out.slice(out.indexOf(x)); }
        out.push(x);
        if (x === 1) return [1];
    }
    return out;
}
console.log(isHappy(98583, 2))